package com.dhf.xhb.dao;

import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.dhf.xhb.domain.Goods;
import com.dhf.xhb.util.*;

public class GoodsHibernateDaoImpl implements GoodsHibernateDao {

	HibernateUtil hu = new HibernateUtil();
	Log log = LogFactory.getLog(this.getClass());

	@Override
	public PageUtil queryByPage(PageUtil page) {
		Session session = this.hu.getSession();
		String hql = "from Goods ";
		String hql2 = "select count(*) from Goods ";
		String orderBy = "goodsIncome";
		String goodsType;// goodsType为字符串类型的数字 可以作为types的下标取值
		Map<String, String> map = page.getSearchInfo();
		// 商品类型
		String[] foods = {"茶", "零食/坚果/特产", "传统滋补营养品", "咖啡/麦片/冲饮", "粮油米面/南北干货/调味品", "保健食品/膳食营养补充食品", "水产肉类/新鲜蔬果/熟食",
				"酒类"};
		String[] clothes = {"女士内衣/男士内衣/家居服", "女装/女士精品", "男装", "运动服/休闲服装"};
		String[] mother = {"童鞋/婴儿鞋/亲子鞋", "童装/婴儿装/亲子装", "孕妇装/孕产妇用品/营养", "尿片/洗护/喂哺/推车床", "玩具/童车/益智/积木/模型",
				"奶粉/辅食/营养品/零食"};
		String[] beauty = {"美容护肤/美体/精油", "彩妆/香水/美妆工具"};
		String[] family = {"厨房/烹饪用具", "购物提货券", "厨房电器", "居家布艺", "家装主材", "全屋定制", "包装", "OTC药品/医疗器械/计生用品", "个性定制/设计服务/DIY",
				"鲜花速递/花卉仿真/绿植园艺", "节庆用品/礼品", "基础建材", "成人用品/情趣用品", "家庭/个人清洁工具", "床上用品", "住宅家具", "家居饰品", "宠物/宠物食品及用品",
				"收纳整理", "餐饮具", "居家日用", "洗护清洁剂/卫生巾/纸/香薰", "个人护理/保健/按摩器材"};
		String[] car = {"电影/演出/体育赛事", "商业/办公家具", "办公设备/耗材/相关服务", "五金/工具", "音乐/影视/明星/音像", "摩托车/装备/配件", "电子元器件市场",
				"自行车/骑行装备/零配件", "电动车/配件/交通工具", "乐器/吉他/钢琴/配件", "电子词典/电纸书/文化用品", "运动/瑜伽/健身/球迷用品", "汽车/用品/配件/改装",
				"书籍/杂志/报纸", "户外/登山/野营/旅行用品"};
		String[] phone = {"生活电器", "影音电器", "3C数码配件", "电脑硬件/显示器/电脑周边", "大家电", "电子/电工", "网络设备/网络相关", "手机",
				"闪存卡/U盘/存储/移动硬盘", "智能设备", "DIY电脑", "电玩/配件/游戏/攻略", "MP3/MP4/iPod/录音笔", "模玩/动漫/周边/cos/桌游", "二手数码",
				"特色手工艺", "平板电脑/MID"};
		String[] shoes = {"隐形眼镜/护理液", "ZIPPO/瑞士军刀/眼镜", "服饰配件/皮带/帽子/围巾", "饰品/流行首饰/时尚饰品新", "美发护发/假发", "女鞋",
				"箱包皮具/热销女包/男包", "运动包/户外包/配件", "运动鞋new", "流行男鞋", "手表", "珠宝/钻石/翡翠/黄金"};
		List<String[]> types = new ArrayList<String[]>();
		types.add(foods);
		types.add(clothes);
		types.add(mother);
		types.add(beauty);
		types.add(family);
		types.add(car);
		types.add(phone);
		types.add(shoes);
		int nowPage = page.getNowPage();
		int pageSize = page.getPageSize();
		if (map != null && !map.isEmpty()) {
			String tempOrderBy = map.get("orderBy");
			String tempGoodsType = map.get("goodsType");
			if (!StringUtil.isEmpty(tempOrderBy)) {
				orderBy = tempOrderBy;
			}
			if (!StringUtil.isEmpty(tempGoodsType)) {
				goodsType = tempGoodsType;
				hql += " where goodsType in :types order by " + orderBy + " desc ";
				hql2 += " where goodsType in :types  ";
				Query query = session.createQuery(hql);
				query.setParameterList("types", types.get(Integer.parseInt(goodsType)));
				query.setFirstResult((nowPage - 1) * pageSize);
				query.setMaxResults(pageSize);
				@SuppressWarnings("unchecked")
				List<Goods> goodses = query.list();
				Query query2 = session.createQuery(hql2);
				query2.setParameterList("types", types.get(Integer.parseInt(goodsType)));
				// query.uniqueResult()获取聚合函数结果为Long类型，需要转化为int类型
				int totalCount = ((Long) query2.uniqueResult()).intValue();
				page.setTotalCount(totalCount);
				int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
				page.setList(goodses);
				page.setTotalCount(totalCount);
				page.setTotalPage(totalPage);
				session.close();
				return page;
			}
		}
		hql += " order by " + orderBy + " desc ";
		Query query = session.createQuery(hql);
		query.setFirstResult((nowPage - 1) * pageSize);
		query.setMaxResults(pageSize);
		@SuppressWarnings("unchecked")
		List<Goods> goodses = query.list();
		Query query2 = session.createQuery(hql2);
		// query.uniqueResult()获取聚合函数结果为Long类型，需要转化为int类型
		int totalCount = ((Long) query2.uniqueResult()).intValue();
		page.setTotalCount(totalCount);
		int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
		page.setList(goodses);
		page.setTotalCount(totalCount);
		page.setTotalPage(totalPage);
		session.close();
		return page;
	}

	@Override
	public Goods queryById(String goodsId) {
		Session session = this.hu.getSession();
		Goods goods = (Goods) session.get(Goods.class, goodsId);
		session.close();
		return goods;
	}

	@Override
	public Map<String, Integer> queryTypesCount() {
		Map<String, Integer> map = new HashMap<String, Integer>();
		Session session = this.hu.getSession();
		String hql = "select count(1) from Goods where goods_type in :types";
		// 各种物品的分类
		String[] foods = {"茶", "零食/坚果/特产", "传统滋补营养品", "咖啡/麦片/冲饮", "粮油米面/南北干货/调味品", "保健食品/膳食营养补充食品", "水产肉类/新鲜蔬果/熟食",
				"酒类"};
		String[] clothes = {"女士内衣/男士内衣/家居服", "女装/女士精品", "男装", "运动服/休闲服装"};
		String[] mother = {"童鞋/婴儿鞋/亲子鞋", "童装/婴儿装/亲子装", "孕妇装/孕产妇用品/营养", "尿片/洗护/喂哺/推车床", "玩具/童车/益智/积木/模型",
				"奶粉/辅食/营养品/零食"};
		String[] beauty = {"美容护肤/美体/精油", "彩妆/香水/美妆工具"};
		String[] family = {"厨房/烹饪用具", "购物提货券", "厨房电器", "居家布艺", "家装主材", "全屋定制", "包装", "OTC药品/医疗器械/计生用品", "个性定制/设计服务/DIY",
				"鲜花速递/花卉仿真/绿植园艺", "节庆用品/礼品", "基础建材", "成人用品/情趣用品", "家庭/个人清洁工具", "床上用品", "住宅家具", "家居饰品", "宠物/宠物食品及用品",
				"收纳整理", "餐饮具", "居家日用", "洗护清洁剂/卫生巾/纸/香薰", "个人护理/保健/按摩器材"};
		String[] car = {"电影/演出/体育赛事", "商业/办公家具", "办公设备/耗材/相关服务", "五金/工具", "音乐/影视/明星/音像", "摩托车/装备/配件", "电子元器件市场",
				"自行车/骑行装备/零配件", "电动车/配件/交通工具", "乐器/吉他/钢琴/配件", "电子词典/电纸书/文化用品", "运动/瑜伽/健身/球迷用品", "汽车/用品/配件/改装",
				"书籍/杂志/报纸", "户外/登山/野营/旅行用品"};
		String[] phone = {"生活电器", "影音电器", "3C数码配件", "电脑硬件/显示器/电脑周边", "大家电", "电子/电工", "网络设备/网络相关", "手机",
				"闪存卡/U盘/存储/移动硬盘", "智能设备", "DIY电脑", "电玩/配件/游戏/攻略", "MP3/MP4/iPod/录音笔", "模玩/动漫/周边/cos/桌游", "二手数码",
				"特色手工艺", "平板电脑/MID"};
		String[] shoes = {"隐形眼镜/护理液", "ZIPPO/瑞士军刀/眼镜", "服饰配件/皮带/帽子/围巾", "饰品/流行首饰/时尚饰品新", "美发护发/假发", "女鞋",
				"箱包皮具/热销女包/男包", "运动包/户外包/配件", "运动鞋new", "流行男鞋", "手表", "珠宝/钻石/翡翠/黄金"};
		List<String[]> types = new ArrayList<String[]>();
		types.add(foods);
		types.add(clothes);
		types.add(mother);
		types.add(beauty);
		types.add(family);
		types.add(car);
		types.add(phone);
		types.add(shoes);
		// 设置各种类型的名字
		String[] typeNames = {"美食", "服装", "母婴", "化妆品", "居家", "文体车品", "数码家电", "鞋包配饰"};
		Query query = session.createQuery(hql);
		int sum = 0;
		for (int i = 0; i < types.size(); i++) {
			// 将类型名字和该类型商品数量添加到map中
			query.setParameterList("types", types.get(i));
			int count = ((Long) query.uniqueResult()).intValue();
			sum += count;
			map.put(typeNames[i], count);
		}
		map.put("全部优惠", sum);
		session.close();
		return map;
	}

	@Override
	public PageUtil queryByKeyPage(PageUtil page) {
		Session session = this.hu.getSession();
		Map<String, String> map = page.getSearchInfo();
		String orderBy = map.get("orderBy");
		LuceneUtil lu = new LuceneUtil();
		Set<String> ids = lu.searchByPage(page);
		if (ids.size() > 0) {
			String hql = "from Goods where goodsId in :ids order by " + orderBy + " desc ";
			Query query = session.createQuery(hql);
			query.setParameterList("ids", ids);
			page.setList(query.list());
		}
		session.close();
		return page;
	}

	@Override
	public void changeCouponPrice() {

		Session session = this.hu.getSession();
		String hql = "from Goods";
		Query query = session.createQuery(hql);
		@SuppressWarnings("unchecked")
		List<Goods> goodses = query.list();
		for (Goods g : goodses) {
			String price = g.getGoodsCouponPrice();
			Pattern p = Pattern.compile("[0-9]+");
			Matcher matcher = p.matcher(price);
			List<String> str = new ArrayList<String>();
			while (matcher.find()) {
				str.add(matcher.group());
			}
			System.out.println(str.size());
			if (str.size() == 1) {
				g.setGoodsCouponPrice(str.get(0));
				session.beginTransaction().begin();
				session.update(g);
				session.beginTransaction().commit();
			} else {
				g.setGoodsCouponPrice(
						(Integer.parseInt(str.get(0)) > Integer.parseInt(str.get(1))) ? str.get(1) : str.get(0));
				session.beginTransaction().begin();
				session.update(g);
				session.beginTransaction().commit();
			}
		}
		System.out.println("更改完毕");
		session.close();
	}

	@Override
	public void insertGoodsFromExcel() {
		String rootPath = "c:\\xhb\\excel";
		Session session = null;
		try {
			File file = new File(rootPath);
			String[] filePaths = file.list();

			if (filePaths.length > 0) {
				File child0 = new File(rootPath + "\\" + filePaths[0]);
				// 如果文件上一次修改时间与当前时间相差一天以上，不进行导入
				if ((new Date().getTime()) - child0.lastModified() < 1000 * 60 * 60 * 24) {
					System.out.println(child0.getName());
					String sql = "truncate table goods_tb";
					JdbcUtil ju = new JdbcUtil();
					ju.updateByPs(sql, null);
					System.out.println("清空表完毕");

					System.out.println("开始导入");
					HibernateUtil hu1 = new HibernateUtil();
					session = hu1.getSession();
					Transaction ta = session.getTransaction();
					InputStream in = new FileInputStream(child0);
					POIFSFileSystem poiFile = new POIFSFileSystem(in);
					HSSFWorkbook workbook = new HSSFWorkbook(poiFile);
					HSSFSheet sheet = workbook.getSheetAt(0);
					int rowNum = sheet.getLastRowNum();
					HSSFRow row = sheet.getRow(0);
					// 从第二行开始遍历excel
					for (int i = 1; i <= rowNum; i++) {
						Goods goods = new Goods();
						row = sheet.getRow(i);
						// 每行从第一列开始取数据
						goods.setGoodsId(row.getCell(0).getStringCellValue().trim());
						goods.setGoodsName(row.getCell(1).getStringCellValue().trim());
						goods.setGoodsPic(row.getCell(2).getStringCellValue().trim());
						goods.setGoodsType(row.getCell(4).getStringCellValue().trim());
						goods.setGoodsBuyUrl(row.getCell(5).getStringCellValue().trim());
						goods.setGoodsPrice(new BigDecimal(row.getCell(6).getStringCellValue().trim()));
						goods.setGoodsSales(Integer.parseInt(row.getCell(7).getStringCellValue().trim()));
						goods.setGoodsIncomeRatio(new BigDecimal(row.getCell(8).getStringCellValue().trim()));
						goods.setGoodsIncome(new BigDecimal(row.getCell(9).getStringCellValue().trim()));
						goods.setGoodsCouponTotal(Integer.parseInt(row.getCell(15).getStringCellValue().trim()));
						goods.setGoodsCouponRemain(Integer.parseInt(row.getCell(16).getStringCellValue().trim()));
						Pattern p = Pattern.compile("[0-9]+");
						Matcher matcher = p.matcher(row.getCell(17).getStringCellValue().trim());
						List<String> str = new ArrayList<String>();
						while (matcher.find()) {
							str.add(matcher.group());
						}
						if (str.size() == 1) {
							goods.setGoodsCouponPrice(str.get(0));
						} else {
							// 如果优惠券需要满足的价格大于商品价格，不保存
							if (((Integer.parseInt(str.get(0)) > Integer.parseInt(str.get(1)))
									? Integer.parseInt(str.get(1))
									: Integer.parseInt(str.get(0))) > new BigDecimal(
											row.getCell(6).getStringCellValue().trim()).intValue()) {
								continue;
							}
							goods.setGoodsCouponPrice((Integer.parseInt(str.get(0)) > Integer.parseInt(str.get(1)))
									? str.get(1)
									: str.get(0));
						}
						goods.setGoodsStartTime(DateUtil.strToDate(row.getCell(18).getStringCellValue().trim()));
						goods.setGoodsEndTime(DateUtil.strToDate(row.getCell(19).getStringCellValue().trim()));
						goods.setGoodsCouponUrl(row.getCell(20).getStringCellValue().trim());
						goods.setGoodsBuyCouponUrl(row.getCell(21).getStringCellValue().trim());
						ta.begin();
						session.save(goods);
						ta.commit();
					}
					ju.closeResource();
				} else {
					this.log.warn("文件过旧，不导入");
				}
				child0.delete();
			} else {
				System.out.println("目录不存在，或者目录为空");
			}
		} catch (FileNotFoundException e) {
			this.log.error("文件未找到");
			e.printStackTrace();
		} catch (IOException e) {
			this.log.error("文件读取失败");
			e.printStackTrace();
		}
		session.close();
		System.out.println("导入完毕");
	}

	@Override
	public void createSearchIndex() {
		String hql = "from Goods ";
		Analyzer analyzer = new IKAnalyzer(true);
		LuceneUtil lu = new LuceneUtil();
		Session session = this.hu.getSession();
		Query query = session.createQuery(hql);
		@SuppressWarnings("unchecked")
		List<Goods> goodses = query.list();
		IndexWriter indexWriter = lu.createIndexWriter("d:/xhb/index", analyzer);
		for (Goods g : goodses) {
			Document doc = new Document();
			doc.add(new Field("goodsId", g.getGoodsId(), TextField.TYPE_STORED));
			doc.add(new Field("goodsName", g.getGoodsName(), TextField.TYPE_STORED));
			doc.add(new Field("goodsType", g.getGoodsType(), TextField.TYPE_STORED));
			try {
				indexWriter.addDocument(doc);
			} catch (IOException e) {
				e.printStackTrace();
				this.log.error("doc添加到indexWriter失败");
			}
		}
		try {
			indexWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
			this.log.error("indexWriter 关闭失败");
		}
		session.close();
		System.out.println("索引创建完毕---------");
	}

}
